<template>
  <div class="page">
    <div class="container">
      <div class="flex-column" style="min-width: 48%">
        <el-form class="form-view">
          <el-form-item label="内容">
            <el-input type="textarea" v-model="prompt" :autosize="{ minRows: 20, maxRows: 30 }"/>
          </el-form-item>
          <div class="btn-container"  >
            <el-button class="btn-gen " :disabled="btnLoading" @click="btnGen" :loading="btnLoading">开始生成</el-button>
            <el-button class="btn-back " :disabled="!resultInfo ||  (resultInfo && resultInfo.text === '')" @click="btnColse">确定方案</el-button>
          </div>
        </el-form>
      </div>
      <div class="result-view" style="height: 630px;max-width: 48%">
        <div class="content-view" v-if="resultInfo && resultInfo.text" ref="aiContentRef">
          <v-md-preview v-if="(abilityType === '1' || abilityType === '2')" :text="resultInfo.text" ></v-md-preview>
          <mind-map v-if="abilityType === '3'" :init-value="resultInfo.text"></mind-map>
        </div>
        <div class="flex-column a_c j_c empty-view flex_1" v-if="!resultInfo">
          <img src="@/assets/wating.png">
          <span> 等待开始…</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import {ElMessage} from "element-plus";
import MindMap from '@/components/mind-map/index.vue'
import MermaidView from "@/components/mermaid-view/index.vue";
import {emitter} from "@/utils/bus";
import {useRoute, useRouter} from "vue-router";
import {useUserStore} from "@/pinia/modules/user";
import { useDataStore } from "@/pinia/modules/data";
import {getAility, getIa, usedAbility} from "@/api/base";

const { proxy, ctx } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const dataStore = useDataStore()
const isStream = ref(false)
const incrementalFlag = ref(false)
const endFlag = ref(false)
const resMesData = ref('')
const isShowText = ref(false)
const showInTerVal = ref(null)
const resultText = ref('')
const btnLoading = ref(false)
const resultInfo = ref(null)
const prompt = ref('')

const abilityType = ref('')
const abilityInfo = ref(null)
const iaInfo = ref(null)

const aiContentRef = ref(null)

const initView = async () => {
  if (route.query && route.query.type) {
    let type = route.query.type
    abilityType.value = type
    const result = await getAility(type)
    abilityInfo.value = result

    const data = await getIa()
    iaInfo.value = data
  }

}

initView()

const btnGen = () => {
  if (!prompt.value) {
    ElMessage.error('请输入内容')
    return
  }
  btnLoading.value = true
  startWrite()
}

const startWrite = () => {
  emitter.on('connect', wsConnect)
  emitter.on('getWsMessage', getMessage)
  proxy.$webSocket.connect(userStore.userInfo.userId)
}

/**
 * socket 链接成功
 */
const wsConnect = () => {
  // 调用请求数据接口
  usedAbilityFn()
}

const autoScroll = () => {
  aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight
}

var usedAbilityId = ''
const usedAbilityFn = async () => {
  let data = {
    intelligentAgentId: iaInfo.value.id,
    abilityId: abilityInfo.value.id,
    prompt: prompt.value,
    sk: userStore.userInfo.userId
  }

  resultInfo.value = { text: '' }
  isShowText.value = true
  isStream.value = true
  endFlag.value = false
  resMesData.value = ''
  resultText.value = ''

  const result = await usedAbility(data)
  resultText.value = result.text
  usedAbilityId = result.recordId
}

/**
 * 接受到 socket 数据
 */
const getMessage = (resp) => {
  // 处理 socket 数据
  if (resp.data === 'SK_NOT_EXIST_ERROR') {
    // this.getAiSkCode();
    return;
  } else if (resp.data === 'SOCKET_CHAT_ERROR') {
    // this.getAiSkCode();
    return;
  } else if (resp.data !== 'SK_NOT_EXIST_ERROR') {
    if (resp.data === 'INCREMENTAL_TRUE') {
      // 增量
      incrementalFlag.value = true
      return
    } else if (resp.data === 'INCREMENTAL_FALSE') {
      // 全量
      incrementalFlag.value = false
      return
    } else if (resp.data === 'WRITE_FINISH') {
      // 写作完成
      endFlag.value = true
      return
    } else {
      resMesData.value += resp.data
      if (isShowText.value) {
        showTextFun()
      }
    }
  }
}

const showTextFun = () => {
  if (!resMesData.value) return
  if (resMesData.value.length === 0) return
  isShowText.value = false
  var i = 0
  showInTerVal.value = setInterval(() => {
    if (i <= resMesData.value.length) {
      var text = resMesData.value.substring(0, i)
      i++
      resultInfo.value.text = text
      autoScroll()
    }
    if (endFlag.value && resultText.value.length === resMesData.value.length) {
      if (resultInfo.value.text.length === resMesData.value.length) {
        closeConnect()
        isStream.value = false
        btnLoading.value = false
        isShowText.value = false
      }
    }
  }, 20)
}


const closeConnect = () => {
  emitter.off('connect', wsConnect)
  emitter.off('getWsMessage', getMessage)
  proxy.$webSocket.close()
  clearInterval(showInTerVal.value)
}

const btnColse = () => {
  if (usedAbilityId) {
    dataStore.setRecordId(usedAbilityId)
    window.close()
  } else {
    ElMessage.error('请先生成内容')
  }
}

</script>

<style lang="scss" scoped>
  .page {
    background: #f1f1f1;
    padding: 0;
    margin: 0;
    min-height: 100vh;
    .container{
      display: flex;
      padding: 30px 40px;
      .form-view {
        background: #fff;
        border-radius: 15px;
        padding: 20px;
        height: 630px;
        position: relative;

        .btn-container {
          position: absolute;
          bottom: 40px;
          width: 94%;
          display: flex;
          align-items: center;
          justify-content: space-around;

          .btn-gen {
            width: 40%;
            height: 60px;
            background: linear-gradient(-18deg, #f4d082, #f4e4ab);
            border-radius: 30px;
            font-size: 16px;
            font-weight: 600 !important;
            color: #a25a14;
            border-color: transparent;
          }

          .btn-back {
            width: 40%;
            height: 60px;
            background: linear-gradient(-18deg,#abcbff,#cdd4f5);
            border-radius: 30px;
            font-size: 16px;
            font-weight: 600 !important;
            color: #fff;
            border-color: transparent;
          }
        }
      }

      .result-view {
        background: #fff;
        flex: 1;
        margin-left: 24px;
        border-radius: 10px;
        padding: 20px;
        display: flex;
        flex-direction: column;
        .content-view {
          overflow: hidden;
          overflow-y: scroll;
          flex: 1;
        }
        .empty-view {
          padding: 5px 15px;
          background: #f1f1f1;
          border: 1px solid #DDDDDD;
          border-radius: 10px;
          margin-bottom: 20px;
          img {
            width: 34px;
            height: 34px;
          }
          span {
            margin-top: 20px;
            font-size: 14px;
            font-weight: 400;
            color: #aaa;
          }
        }
      }
    }
  }
</style>
